package qsoft.com.tp51_test

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.*
import qsoft.com.tp51_scanner_module.TP51_Scanner
import qsoft.com.tp51_sn_module.TP51_SN
import qsoft.com.tp51_test.ShareUtils.putString

class MainActivity : AppCompatActivity() {

    private var _scanner: TP51_Scanner? = null

    private val REQUESTED_PERMISSIONS = arrayOf(
        Manifest.permission.READ_PHONE_STATE
    )

    private val PERMISSION_REQ_ID = 22

    fun btnClear_Click(v: View) {
        txtResult.setText("")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)
        initCtrl()

        if (!checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID)) {
            MaterialDialog(this).show {
                message(text = "获取权限失败，程序无法运行")
                positiveButton { it.dismiss();finish() }
                lifecycleOwner(this@MainActivity)
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        Log.d(
            "q-soft",
            "onRequestPermissionsResult " + grantResults[0].toString() + " " + requestCode
        )

        when (requestCode) {
            PERMISSION_REQ_ID -> {
                if (grantResults[0] !== PackageManager.PERMISSION_GRANTED) {
                    MaterialDialog(this).show {
                        message(text = "Need permissions " + Manifest.permission.RECORD_AUDIO + "/" + Manifest.permission.CAMERA + "/" + Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        positiveButton(text = "确定") {
                            it.dismiss()
                        }
                    }
                }
            }
        }
    }


    fun checkSelfPermission(permission: String, requestCode: Int): Boolean {
        Log.d("q-soft", "checkSelfPermission $permission $requestCode")
        if (ContextCompat.checkSelfPermission(
                this,
                permission
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(this, REQUESTED_PERMISSIONS, requestCode)
            return false
        }
        return true
    }

    private fun initCtrl() {
        btnClear.setOnClickListener(this::btnClear_Click)


        val action = ShareUtils.getString(this, "action", "com.qs.scancode")!!
        val data = ShareUtils.getString(this, "data", "data")!!

        _scanner = TP51_Scanner(this.lifecycle, action, data).also { it ->
            it.setOnReceivedKotlin(this) { data ->
                txtResult.text.appendLine(data)
                Log.v("q-soft", data)
            }
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.main_menu, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.miAbout -> {
                val sn =
                    TP51_SN().getSerialNumber() //调用 qsoft.com.tp51_sn_module.TP51_SN.getSerialNumber() 读取本机序列号
                alert("序列号：$sn\r\n\r\n", "关于").show()
            }
            R.id.miBroadcast -> {
                alert {
                    customView {
                        verticalLayout {
                            var action = editText(_scanner!!.action) {
                                hint = "扫描广播的action"
                            }.lparams {
                                width = matchParent
//                                horizontalMargin = 60
                                verticalMargin = 20
                            }

                            var data = editText(_scanner!!.data) {
                                hint = "扫描广播的extra key"
                            }.lparams {
                                width = matchParent
//                                horizontalMargin = 60
                                verticalMargin = 20
                            }

                            positiveButton("确认") {
                                ShareUtils.also {
                                    putString(this@MainActivity, "action", action.text.toString())
                                    putString(this@MainActivity, "data", data.text.toString())
                                }
                                _scanner!!.action = action.text.toString()
                                _scanner!!.data = data.text.toString()
                                _scanner!!.setOnReceivedKotlin(this@MainActivity) { data ->
                                    txtResult.text.appendLine(data)
                                    Log.v("q-soft", data)
                                }
                            }

                            negativeButton("取消") {
                                it.dismiss()
                            }
                        }
                    }
                }.show()
            }
        }

        return super.onOptionsItemSelected(item)
    }
}
